<template>
  <div class="app-container">

    <div class="box ph-30">
      <div class="panel">
        <div class="panel-header">
          <h3 class="panel-title">填写报名信息</h3>
        </div>
        <div class="panel-body">
          <el-form ref="ruleFormRef" label-width="120px" class="signForm" :model="form" :rules="rules">
            <el-row>
              <el-col :span="8" :offset="2">
                <el-form-item label="参赛队logo" prop="imgUrl">
                  <ImageUpload2 v-model="form.imgUrl" class="bili43" :crop-width="400" :crop-height="300" :limit="1" />
                  <!-- <span class="tip"><i>*</i>请上传近期 彩色免冠照片</span> -->
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="参赛队名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入参赛队名称" />
                </el-form-item>
                <el-form-item label="参赛队简称" prop="abreviations">
                  <el-input v-model="form.abreviations" />
                </el-form-item>
                <el-form-item label="参赛队类型" prop="type">
                  <el-select v-model="form.type" placeholder="请选择参赛队类型" style="width: 100%;">
                    <el-option label="俱乐部" value="0" />
                    <el-option label="事业单位" value="1" />
                    <el-option label="道馆" value="2" />
                    <el-option label="企业" value="3" />
                    <el-option label="机关" value="4" />
                    <el-option label="其他" value="5" />
                  </el-select>
                </el-form-item>
                <!--                <el-form-item v-if="form.type==3" label="企业性质" prop="ctype">-->
                <!--                  <el-select v-model="form.ctype" placeholder="请选择企业性质" style="width: 100%;">-->
                <!--                    <el-option label="国资企业（含央企和本地）" value="0" />-->
                <!--                    <el-option label="外商投资企业" value="1" />-->
                <!--                    <el-option label="港澳台企业" value="2" />-->
                <!--                    <el-option label="民营企业" value="3" />-->
                <!--                    <el-option label="商会组织" value="4" />-->
                <!--                    <el-option label="其他" value="5" />-->
                <!--                  </el-select>-->
                <!--                </el-form-item>-->

                <el-form-item label="联系人" prop="contactPerson">
                  <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactTelno">
                  <el-input v-model="form.contactTelno" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="所在地区" prop="regionId">
                  <el-cascader
                    v-model="form.regionId"
                    style="width: 100%;"
                    :options="regionsList"
                    :props="{ label:'text' }"
                  />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                  <el-input
                    v-model="form.address" placeholder="请输入详细地址"
                    :rows="2"
                    type="textarea"
                  />
                </el-form-item>

              </el-col>
            </el-row>
            <el-row v-if="participantsInfoArr&&participantsInfoArr.length>0">
              <el-col :span="16" :offset="4">
                <h3>补充信息</h3>
                <el-form-item v-for="(s,index) in participantsInfoArr" :key="index">
                  <template #label>
                    <span v-if="s.status == 0" class="red">*</span>{{ s.name }}
                  </template>
                  <el-input v-if="s.type == '0'" v-model="s.value" />
                  <el-input v-if="s.type == '1'" v-model="s.value" type="number" />
                  <el-select v-if="s.type == '4'" v-model="s.value" class="m-2">
                    <el-option v-for="item in s.option" :key="item.id" :label="item.name" :value="item.name" />
                  </el-select>
                  <ImageUpload v-if="s.type == '3'" v-model="s.value" :limit="1" :is-show-tip="false" />
                  <!-- 文件 2-->
                  <FileUpload v-if="s.type == '2'" v-model="s.fixWxFile" :action="uploadUrl" :accept="accept" />

                </el-form-item>
              </el-col>
            </el-row>

            <!-- 队伍 -->
            <Ranks v-if="isRanks" :coach-or-leader-flag="coachOrLeaderFlag" />
          </el-form>

        </div>
        <div class="panel-footer text-center">
          <el-button type="success" plain round @click="goPrev()">上一步</el-button>

          <el-button type="success" round @click="submitForm()">下一步</el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
import { useRoute, useRouter } from 'vue-router'
import { toRefs } from '@vueuse/shared'
import Ranks from './components/isRanks'

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
import * as match from '@/api/match/pc'
import { ElMessage } from 'element-plus'
import _ from 'lodash'

const data = reactive({
  isRanks: false,
  form: {},
  groupId: 0,
  cptId: 0,
  signType: false,
  regionsList: [],
  participantsInfoArr: [],
  rankList: [],
  accept: '.doc, .pdf, .docx, .zip',
  rules: {
    imgUrl: { required: true, message: '请上传参赛队图标', trigger: 'blur' },
    name: { required: true, message: '请填写参赛队名称', trigger: 'blur' },
    type: { required: true, message: '请选择参赛队类型', trigger: 'change' },
    // ctype: { required: true, message: '请选择企业性质', trigger: 'change' },
    regionId: { required: true, message: '请选择所在地区', trigger: 'change' },
    contactPerson: { required: true, message: '请填写联系人', trigger: 'blur' },
    contactTelno: { required: true, message: '请填写联系方式', trigger: 'blur' },
    abreviations: { required: true, message: '请填写参赛队简称', trigger: 'blur' },
    address: { required: true, message: '请填写详细地址', trigger: 'blur' }
  },
  coachOrLeaderFlag: ''
})
const {
  isRanks,
  rankList,
  form,
  groupId,
  signType,
  participantsInfoArr,
  cptId,
  rules,
  regionsList,
  coachOrLeaderFlag, accept
} = toRefs(data)
const uploadUrl = ref('/upload/upLoadToFileServer')

onMounted(() => {
  // 获取参赛队信息
  groupId.value = route.query.groupId
  getGroupInfo()
  cptId.value = route.query.matchId
  signType.value = route.query.signType
  if (signType.value == 2) {
    isRanks.value = true
  }
  getRegionsList()
  match.getMatchById({ id: cptId.value }).then(res => {
    coachOrLeaderFlag.value = res.data.coachOrLeaderFlag
    if (res.data.groupInfo) {
      participantsInfoArr.value = JSON.parse(res.data.groupInfo)
    }

    // 获取补充信息
    match.getMyGroupForCpt(groupId.value, cptId.value).then(res => {
      if (res.data.groupInfo && res.data.groupInfo.groupInfo) {
        const groupInfo = JSON.parse(res.data.groupInfo.groupInfo)
        if (groupInfo.length > 0) {
          // 补充字段信息
          participantsInfoArr.value = groupInfo
          for (var n of participantsInfoArr.value) {
            if (n.type == '3' && n.value.url) {
              // 图片
              n.value = n.value.url
            }
            if (n.type == '2') {
              // 文件
              var arr = [{
                name: n.value.name,
                url: n.value.url
              }]
              n.fixWxFile = arr
            }
          }
        }
      }
    })
  })
})

function getRegionsList() {
  match.regionsList().then(res => {
    regionsList.value = res.data
  })
}

function getGroupInfo() {
  if (groupId.value == 0) {
    // 新参赛队
    return
  }
  match.getGroupById(groupId.value).then(res => {
    form.value = res.data
  })
}

function getTeamList() {
  return match.getMyTeamList(cptId.value, groupId.value).then(response => {
    rankList.value = response.data
  })
}

function goPrev() {
  router.go(-1)
}

function submitForm() {
  proxy.$refs['ruleFormRef'].validate((valid, fields) => {
    if (valid) {
      console.log(form.value)
      if (typeof (form.value.regionId) === 'object') {
        form.value.regionId = _.last(form.value.regionId)
      }

      for (const n of participantsInfoArr.value) {
        if (n.status == 0 && (!n.value && !n.fixWxFile)) {
          ElMessage.error(`请完善${n.name}信息`)
          return
        }
      }

      if (participantsInfoArr.value) {
        // 保存补充信息
        let fileInfo = {}
        for (var p of participantsInfoArr.value) {
          if (p.type == '2' && p.fixWxFile) {
            const temp = p.fixWxFile[0].name.split('.')
            fileInfo = {
              url: p.fixWxFile[0].url,
              name: p.fixWxFile[0].name,
              extname: temp[temp.length - 1]
            }
            p.value = fileInfo
          }
        }
        const obj = {
          cptId: cptId.value,
          groupId: groupId.value,
          groupInfo: JSON.stringify(participantsInfoArr.value)
        }
        match.saveMyGroupExtraInfo(obj).then(res => {

        })
      }
      // 保存参赛队信息
      match.saveMyGroup(form.value).then(res => {
        groupId.value = res.data
        getTeamList().then(res => {
          if (isRanks.value && rankList.value.length == 0) {
            ElMessage.error('至少有一个队伍')
            return
          }
          goNext()
        })
      })
    } else {
      console.log(form.value, fields)
    }
  })
}

function goNext() {
  if (coachOrLeaderFlag.value == '1' && !isRanks.value) {
    // 选教练
    router.push({
      name: `chooseCoach`,
      query: {
        matchId: cptId.value,
        groupId: groupId.value,
        signType: signType.value
      }
    })
  } else {
    // 选运动员
    router.push({
      name: `chooseSportsman`,
      query: {
        matchId: cptId.value,
        groupId: groupId.value,
        signType: signType.value
      }
    })
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 0;
  background: #F5F7F9;
}

.panel-footer .el-button--success {
  padding: 0 40px;
}
.bili43{
  :deep(.fileItem) {
    width: 200px;
    height: 150px;
  }

  .el-upload-list--picture-card .el-upload-list__item {
    width: 200px;
    height: 150px;
  }
}
.signForm {
  .el-form-item__label {
    color: #4C5359;
  }
}

.tip {
  font-size: 13px;
  color: #999;
  margin: 10px 0;

  i {
    color: red;
    margin: 0 4px 0 0;
  }
}

.threeFour {
  width: 100%;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}

.red {
  color: #f56c6c;
}
</style>
